<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\common\controller\Backend;
use app\common\library\Upload;
use app\common\model\SmsRecord;
use jueqi\AliYunSms;
use think\Exception;
use think\exception\FileException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Event;

/**
 * Ajax请求控制器
 */
class Ajax extends Backend
{
    /**
     * 无需鉴权的方法
     */
    protected $noNeedPermission = ['*'];

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 富文本上传文件接口
     */
    public function editorUpload()
    {
        AdminLog::setTitle(__('upload'));
        $file = $this->request->file('file');
        try {
            $upload     = new Upload($file);
            $attachment = $upload->upload(null, $this->auth->id);
            unset($attachment['create_time'], $attachment['quote']);
            if ($attachment['code'] === 1) {
                if(!isset($attachment['data'])){
                    $this->editorSuccess([
                        'errno'   => 2,
                        "message" => '上传失败！',
                    ]);
                }
                $url = $attachment['data']['url'] ?? '';
                $topic = $attachment['data']['topic'] ?? '';
                if(empty($url)){
                    $this->editorSuccess([
                        'errno'   => 2,
                        "message" => '上传失败！',
                    ]);
                }
                if($topic === 'default'){
                    $redirect_uri = getURL();
                    $domain = request()->domain();
                    if (strstr($redirect_uri, '/addons/')) {
                        $redirect_uri = $domain . '/addons/jueqi_survey_pro/public';
                    } else {
                        $redirect_uri = $domain;
                    }
                    $url = $redirect_uri . $url;
                }
                $this->editorSuccess([
                    "errno" => 0, // 注意：值是数字，不能是字符串
                    "data"  => [
                        "url"  => $url, // 图片 src ，必须
                        "alt"  => $attachment['data']['name'] ?? '', // 图片描述文字，非必须
                        "href" => "" // 图片的链接，非必须
                    ]
                ]);
            }
            $this->editorSuccess([
                'errno'   => 2,
                "message" => '上传失败！',
            ]);
        } catch (Exception|FileException $e) {
            $this->editorSuccess([
                'errno'   => 3,
                "message" => '上传异常！',
            ]);
        }
    }

    /**
     * 上传文件接口
     */
    public function upload()
    {
        AdminLog::setTitle(__('upload'));
        $file = $this->request->file('file');
        try {
            $config = [];
            // 查找远程附件配置
            $storageConfig = get_sys_config("storage_config");
            if ($storageConfig !== 'local') {
                if ($storageConfig === 'oss') {
                    $config['topic'] = 'oss_cos_cloud';
                } else if ($storageConfig === 'cos') {
                    $config['topic'] = 'cos_cloud';
                }
                $config['storage']  = $storageConfig;
                $config['savename'] = "/jueqi_survey_pro/{topic}/{year}{mon}{day}/{filesha1}{.suffix}";
            }
            $upload = new Upload($file, $config);
            $res    = $upload->upload(null, $this->auth->id);
            if ($res['code'] == 2) {
                $this->error($res['msg']);
            }
            $attachment = $res['data'];
            unset($attachment['create_time'], $attachment['quote']);
        } catch (Exception|FileException $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('File uploaded successfully'), [
            'file' => $attachment ?? []
        ]);
    }

    public function area()
    {
        $this->success('', get_area());
    }

    public function buildSuffixSvg()
    {
        $suffix     = $this->request->param('suffix', 'file');
        $background = $this->request->param('background');
        $content    = build_suffix_svg((string)$suffix, (string)$background);
        return response($content, 200, ['Content-Length' => strlen($content)])->contentType('image/svg+xml');
    }

    public function getTablePk($table = null)
    {
        if (!$table) {
            $this->error(__('Parameter error'));
        }
        $tablePk = Db::query("SHOW TABLE STATUS LIKE '$table'", [], true);
        if (!$tablePk) {
            $table   = config('database.connections.mysql.prefix') . $table;
            $tablePk = Db::query("SHOW TABLE STATUS LIKE '$table'", [], true);
            if (!$tablePk) {
                $this->error(__('Data table does not exist'));
            }
        }
        $tablePk = Db::table($table)->getPk();
        $this->success('', ['pk' => $tablePk]);
    }

    public function getTableFieldList()
    {
        $table = $this->request->param('table');
        $clean = stringToBoolean($this->request->param('clean', true));
        if (!$table) {
            $this->error(__('Parameter error'));
        }

        $tablePk = Db::name($table)->getPk();
        $this->success('', [
            'pk'        => $tablePk,
            'fieldlist' => get_table_fields($table, $clean),
        ]);
    }

    public function clearCache()
    {
        $type = $this->request->post('type');
        if ($type == 'tp' || $type == 'all') {
            Cache::clear();
        } else {
            $this->error(__('Parameter error'));
        }
        Event::trigger('cacheClearAfter', $this->app);
        $this->success(__('Cache cleaned~'));
    }

    /**
     * 发送短信
     * @return void
     */
    public function sendSms($mobile, $content = '', $templateCode = '', $activity_id = 0)
    {
        if (empty($mobile)) {
            $this->error('手机号不能为空！');
        }
        if (empty($content)) {
            $this->error('短信内容不能为空！');
        }
        if (empty($templateCode)) {
            $this->error('短信模板编号不能为空！');
        }
        if (is_array($content)) {
            $content = json_encode($content);
        }
        $msg   = '';
        $class = new AliYunSms();
        $res   = $class->sendSms($mobile, $content, $templateCode, $msg);

        $data = array(
            'type'            => 1,
            'mobile'          => $mobile,
            'content'         => $content,
            'activity_id'     => $activity_id,
            'template_number' => $templateCode,
            'create_time'     => time(),
        );
        // 增加发送短信记录
        $model = new SmsRecord();
        if (!$res) {
            $data['status'] = 2;
            $data['message']= $msg;
            $model->save($data);
            $this->error($msg);
        }
        $data['status'] = 1;
        $model->save($data);
        $this->success('发送成功！');
    }

}
